import React, { useState, useEffect, forwardRef } from 'react';
import { Input, Modal, Button, Tree, Select } from 'antd';
import { ExportOutlined } from '@ant-design/icons';
import { getNewsCategory } from '../../service';
import { InbizIcon } from '@inbiz/utils';
import './cate.less';

const NewsCate: React.FC<News.INewsCateProps> = forwardRef((props, ref) => {
  const { value, onChange } = props;
  const [visible, setVisible] = useState(false);
  const [selectedRecord, setSelectRecord] = useState<News.INewsCateValueType>(
    value as News.INewsCateValueType,
  );
  const [treeData, setTreeData] = useState<Array<News.TreeDataSource>>([
    {
      key: '0000-0000-0001',
      title: '新闻',
      children: [],
    },
  ]);
  const [searchOptions, setSearchOptions] = useState<Array<News.NewsCategory>>([]);
  const [expandedKeys, setExpandedKeys] = useState<Array<string>>(['0000-0000-0001']);

  const toggleVisible = () => {
    setVisible(!visible);
  };

  const getCateList = async (callback: Function, categoryName?: string) => {
    try {
      const res = await getNewsCategory({
        categoryName,
      });
      callback(res);
    } catch (e) {
      console.error(e);
    }
  };

  useEffect(() => {
    getCateList((res: any) => {
      setTreeData([
        {
          key: '0000-0000-0001',
          title: '新闻',
          children: (res?.CmsCategoryList || []).map((i: News.NewsCategory) => ({
            key: i.Key,
            title: i.Title,
          })),
        },
      ]);
    });
  }, []);

  const handleSelect = (selectedKeys: any, e: any) => {
    const { selected, node } = e;
    if (!selected) {
      setSelectRecord(undefined as any);
    } else {
      setSelectRecord({
        key: node.key,
        title: node.title,
      });
    }
  };

  const handleOk = () => {
    onChange && onChange(selectedRecord as any);
    toggleVisible();
  };

  const handleSearch = (categoryName: string) => {
    getCateList((res: any) => {
      setSearchOptions(res?.CmsCategoryList || []);
    }, categoryName);
  };

  const handleChange = (value: string, record: any) => {
    if (value) {
      setSelectRecord({
        key: value,
        title: record.children,
      });
      setExpandedKeys([...expandedKeys, value]);
    }
  };

  const handleExpand = (expandedKeys: any) => {
    setExpandedKeys(expandedKeys);
  };

  return (
    <div>
      <Input onClick={toggleVisible} value={selectedRecord?.title} readOnly />
      <Modal
        title="分类选择"
        visible={visible}
        onOk={handleOk}
        onCancel={toggleVisible}
        okText="确定"
        cancelText="取消"
      >
        <div className="cate-select-wrapper">
          <Select
            className="cate-select"
            showSearch
            onSearch={handleSearch}
            onChange={handleChange}
            notFoundContent={null}
            filterOption={false}
          >
            {searchOptions.map((i) => (
              <Select.Option key={i.Key}>{i.Title}</Select.Option>
            ))}
          </Select>
          <Button
            onClick={() => window.open('/inbiz/admin#/content-manage/cms/newsManage')}
            className="edit-btn"
            type="primary"
            icon={<ExportOutlined />}
          >
            前往编辑
          </Button>
        </div>
        <Tree
          showIcon
          icon={<InbizIcon type="icon-xinwen" style={{ color: 'rgb(25, 137, 250)' }} />}
          autoExpandParent
          treeData={treeData}
          expandedKeys={expandedKeys}
          selectedKeys={[selectedRecord?.key]}
          onSelect={handleSelect}
          onExpand={handleExpand}
        />
      </Modal>
    </div>
  );
});

export default NewsCate;
